package com.arvato.wxwork.controller.admin.staff;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.wxwork.bean.bean_dto.WxworkDepartmentNodeDto;
import com.arvato.wxwork.service.staff.WxworkDepartmentService;


/**
 * 企业微信门店管理Controller
 * @author zhan655
 *
 */
@Controller
@RequestMapping("/admin/wxwork/department/")
public class WxworkDepartmentController {
	
	private Logger logger = LoggerFactory.getLogger(WxworkDepartmentController.class);

	@Autowired
	private WxworkDepartmentService wxworkDepartmentService;
	
	
	
	@RequestMapping("index")
    public String index(){
        return "/static/pages/index.html";
    }
	
	
	/**
	 * 部门树查询接口
	 * @param req
	 * @param departmentId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/tree")
	public Result departmentTree(HttpServletRequest req, @RequestParam(value = "userId", defaultValue = "0")Integer departmentId) {
		logger.info("获取部门树");
		List<WxworkDepartmentNodeDto> departmentTree = null;
		try {
			departmentTree = wxworkDepartmentService.getDepartmentTree(departmentId);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail("获取部门树失败" + e);
		}
		return Result.success(departmentTree);
	}
	
	/**
	 * 创建部门
	 * @param req
	 * @param name
	 * @param code
	 * @param parentid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/create")
	public Result create(HttpServletRequest req, String name, String code, int parentid) {
		logger.info("创建一个部门节点");
		// 验证部门code的合法性
		List<WxworkDepartmentNodeDto> departmentList = wxworkDepartmentService.getDepartmentTree(1);
		// 新建一级次级部门不需要验证code
		if(parentid != 1) {
			for(WxworkDepartmentNodeDto node : departmentList) {
				String nodeName = node.getName();
				if(nodeName.contains("(") && nodeName.contains(")")) {
					String oldCode = node.getName().split("\\(")[1].split("\\)")[0];
					if(oldCode.equals(code)) {
						return Result.fail("部门编码已存在。");
					}
				}
			}
			// 子部门的编码 必须以父部门的编码为开通
			for(WxworkDepartmentNodeDto node : departmentList) {
				int pid = node.getId();
				if(pid == parentid) {
					String parentCode = node.getName().split("\\(")[1].split("\\)")[0];
					if(!code.startsWith(parentCode)) {
						return Result.fail("子部门编码不符合规范，子部门编码需要以父级部门的编码为开头");
					}
				}
			}
		}
		try {
			wxworkDepartmentService.create(name + "(" + code + ")", parentid);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail("创建部门失败：" + e.getMessage());
		}
		return Result.success("创建部门成功。");
	}
	
	/**
	 * 更新部门 更新的话 只能更新部门的名称（前台把code给disable掉）
	 * @param req
	 * @param id
	 * @param name
	 * @param code 前台要穿过来
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/update")
	public Result update(HttpServletRequest req, int id, String name, String code) {
		logger.info("更新一个部门节点");
		if(name == null || name.equals("") || code == null || code.equals("")) {
			return Result.fail("部门参数不合法");
		}
		try {
			wxworkDepartmentService.update(id, name + "(" + code + ")");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail("删除部门失败：" + e.getMessage());
		}
		
		return Result.success("删除部门成功。");
	}
	
	/**
	 * 删除部门
	 * @param req
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delete")
	public Result delete(HttpServletRequest req, int id) {
		logger.info("更新一个部门节点");
		try {
			wxworkDepartmentService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail("更新部门失败：" + e.getMessage());
		}
		return Result.success("更新部门成功。");
	}
	
}

